import { Component } from 'react';
import { nanoid } from 'nanoid'
import axios from 'axios'
import bus from '../../util/bus';
import MyInterview from '../../component/MyInterview/MyInterview';

import './Home.css'

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      useremail: this.props.useremail,
      interviewIdInput: '',
      warning: false,
      loginWarning: false,
    }
  }
  
  render () {
    return (
      <div id="home">
        <input className="interviewid-input" placeholder="请输入面试房间Id" onChange={this.interviewIdHandler}
          value={this.state.interviewCodeInput}>
        </input>
        <div className="interview-join-button" onClick={this.interviewJoinHandler}>
          加入面试房间
        </div>
        <div className="warning" style={{ display: this.state.warning ? "block" : "none" }}>
          面试房间id错误，没有这个面试房间
        </div>
        <div className="interview-create-button" onClick={this.interviewCreateHandler}>
          创建面试房间
        </div>
        <div className="warning" style={{ display: this.state.loginWarning ? "block" : "none" }}>请先登录或注册</div>
        <div className="my-interviews-tag">我的面试房间</div>
        <MyInterview useremail={this.state.useremail} />
      </div>
    )
  }

  interviewCreateHandler = () => {
    const { useremail } = this.state;
    if(useremail == null || useremail == ''){
      this.setState({
        loginWarning: true,
      })
      return;
    }
    const newInterview = {
      interviewId: nanoid(),
      useremail: useremail,
    }
    axios.post('https://qcge2v.fn.thelarkcloud.com/addInterview', newInterview).then(()=>{
      bus.emit('MyInterviewUpdate');
    });
    
  }

  interviewJoinHandler = () => {
    if(this.state.useremail == null || this.state.useremail == ''){
      this.setState({
        loginWarning: true,
      })
      return;
    }
    let that = this
    let url = 'https://qcge2v.fn.thelarkcloud.com/getInterview?interviewId=';
    const interviewId = this.state.interviewIdInput;
    url += interviewId;
    axios.get(url).then((resp) => {
      if (resp.data.result != null) {
        const { routeProps } = that.props;
        routeProps.history.push('/interview-room', {
          useremail: that.state.useremail,
          interviewId: interviewId
        })
      }
      else {
        that.setState({
          warning: true
        })
      }
    })
  }


  interviewIdHandler = (e) => {
    this.setState({
      interviewIdInput: e.target.value
    })
  }
}